<html>
<p>
<form action="query.php" method="GET">
<textarea name="query" cols="60" rows="8">
</textarea>
<input type="submit" value="Submit" />
</form>
</p>

<?php
$input = $_GET["query"];

if(isset($input) && $input != ""){
echo "<h3>Results:</h3>";
$db_connection = mysql_connect("localhost", "cs143", "");

if (!$db_connection) {
$errmsg = mysql_error($db_connection);
    print "Connection failed: $errmsg <br />";
    exit(1);
}

$db_selected = mysql_select_db("CS143", $db_connection);
if(!db_selected){
    print "Table Selection failed <br />";
    exit(1);
}

$query = "$input"; 
$db_query = mysql_query($query, $db_connection);
if(!$db_query){
    print "Query failed: Invalid SQL query <br />";
    exit(1);
}


$fields_num = mysql_num_fields($db_query);

echo "<h3>Results:</h3>";
echo "<table border ='1'><tr>";
for ($i = 0; $i < $fields_num; $i++)
{
$field = mysql_fetch_field($db_query);
echo "<td>$field->name</td>"; 
}
echo "</tr>";

while($row = mysql_fetch_row($db_query)) {
echo "<tr>";

foreach ($row as $cell){
if ($cell == NULL)
echo "<td>N/A</td>";
else
echo "<td>$cell</td>";

}

echo "</tr>\n";

}

}
?>
</html>
